/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package da523b;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 *
 * @author linuslofberg
 */
public class Sql {

    private Connection connect = null;
    private Statement statement;
    private ResultSet rs;

    public void connect() {

        try {
            String url = "jdbc:mysql://194.47.32.124:3306/phonebook";
            Properties info = new Properties();
            info.put("user", "arduino");
            info.put("password", "smultron");

            connect = DriverManager.getConnection(url, info);

            if (connect != null) {
                System.out.println("Connected to the database Phonebook");
            }

        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    public ResultSet search(String q) throws SQLException {

        if (connect == null || connect.isClosed()) {
            connect();
        }

        try {

            statement = connect.createStatement();
            rs = statement.executeQuery(q);

            return rs;

        } catch (SQLException ex) {
            ex.printStackTrace();
            return null;
        }
    }

    public void insert(String firstName, String lastName, String phoneNumber) throws SQLException {
        if (connect == null || connect.isClosed()) {
            connect();
        }
        
        String query = "INSERT INTO  `phonebook`.`phonebook` (`id` ,`fornamn` ,`efternamn` ,`telefon`)VALUES (NULL ,  '" + firstName + "',  '" + lastName + "',  '" + phoneNumber + "');";

        try {
            statement = connect.createStatement();
            statement.executeUpdate(query);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    public void update(String q) throws SQLException {
        if (connect == null || connect.isClosed()) {
            connect();
        }

        try {
            statement = connect.createStatement();
            statement.executeUpdate(q);

        } catch (SQLException ex) {
            ex.printStackTrace();

        }
    }
}
